package online.afeibaili.storebackendframework.service.impl

import online.afeibaili.storebackendframework.model.ProductEntity
import online.afeibaili.storebackendframework.repository.ProductRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*
import kotlin.jvm.optionals.getOrNull


/**
 * 商品实现
 *
 *@author AfeiBaili
 *@version 2025/10/17 15:46
 */

@Service
@Transactional
class ProductServiceImpl {
    @Autowired
    lateinit var repository: ProductRepository

    fun create(product: ProductEntity): ProductEntity {
        return repository.save(product)
    }

    fun addSales(productId: Long, number: Int) {
        getById(productId)?.let { it ->
            it.sales += number
            repository.save(it)
        }
    }

    fun getPointsProduct(page: Int, count: Int): List<ProductEntity> {
        return repository.findByIsPoints(true, PageRequest.of(page, count))
    }

    fun getByHot(page: Int, count: Int): List<ProductEntity> {
        val page: Page<ProductEntity> = repository.findAllByOrderBySalesDesc(PageRequest.of(page, count))
        return page.toList()
    }

    fun getByPrice(page: Int, count: Int): List<ProductEntity> =
        repository.findAllByOrderByPriceDesc(PageRequest.of(page, count)).toList()

    fun getByPage(page: Int, count: Int): List<ProductEntity> {
        val page: Page<ProductEntity> = repository.findAllBy(PageRequest.of(page, count))
        return page.toList()
    }

    fun getKeyWordByNameAndDetail(keyWord: String, page: Int, count: Int): List<ProductEntity> {
        return repository.findByNameContainingOrDetailContaining(
            keyWord,
            keyWord,
            PageRequest.of(page, count)
        ).toList()
    }

    //sort只能是 asc和desc
    fun getByPage(page: Int, count: Int, type: String, sort: String): List<ProductEntity> {
        val orders: Sort = when (sort) {
            "asc" -> Sort.by(Sort.Direction.ASC, type)
            "desc" -> Sort.by(Sort.Direction.DESC, type)
            else -> Sort.by(Sort.Direction.DESC, type)
        }
        val pageRequest: PageRequest = PageRequest.of(page, count, orders)
        return repository.findAll(pageRequest).toList()
    }

    fun getRandomProduct(count: Int): List<ProductEntity> {
        return repository.findRandom(count)
    }

    fun getProducts(ids: List<Long>): List<ProductEntity> {
        return repository.findByCreateTimeIn(ids)
    }

    fun getById(id: Long): ProductEntity? {
        val optional: Optional<ProductEntity> = repository.findById(id)
        return optional.getOrNull()
    }

    fun getAll(): List<ProductEntity> {
        return repository.findAll()
    }
}